<template>
  <div>
    <!-- 标题栏 -->
    <van-nav-bar title="登录" />
    <!-- 表单栏 -->
    <van-form @submit="loginFn">
      <van-field
        required
        v-model="mobile"
        label="手机号"
        placeholder="请输入手机号"
        :rules="rules.mobile"
      />
      <van-field
        required
        v-model="code"
        type="number"
        label="验证码"
        placeholder="请输入验证码"
        :rules="rules.code"
      />
      <div style="margin: 16px;">
        <van-button
          :loading="isDone"
          loading-text="登录中..."
          :disabled="isDone"
          round
          block
          type="info"
          native-type="submit"
          >提交</van-button
        >
      </div>
    </van-form>
  </div>
</template>

<script>
import { userLogin } from '@/api/user'
import { mapMutations } from 'vuex'
export default {
  name: 'Login',
  data() {
    return {
      mobile: '',
      code: '',
      rules: {
        mobile: [
          // 必填项
          { required: true, message: '请填写手机号' },
          // pattern 正则
          { pattern: /^1[3-9]\d{9}$/, message: '手机号码格式不正确' }
        ],
        code: [
          // 必填项
          { required: true, message: '请填写验证码' },
          // pattern 正则
          { pattern: /^\d{6}$/, message: '验证码格式不正确' }
        ]
      },
      isDone: false
    }
  },

  methods: {
    ...mapMutations('user', ['setToken']),
    async loginFn() {
      this.isDone = true
      // console.log('发送中...')
      try {
        const res = await userLogin(this.mobile, this.code)
        // console.log(res)
        // localStorage.setItem(JSON.stringify('hm', res.data))
        this.$toast.success('登录成功')

        // 本地存储
        this.setToken(res.data)
        // 将token数据存储到vuex中
        this.$store.commit('setToken', res.data)

        // 登录成功后跳转页面
        console.log(this.$route.query.back)
        const back = this.$route.query.back
        const flag = this.$route.query.flag
        // 跳转
        // 判断back的有无, 有的跳转到back
        if (back) {
          if (flag) {
            this.$router.back(back)
          } else {
            this.$router.push(back)
          }
          // 没有的跳转到首页
        } else {
          this.$router.push('/')
        }
      } catch (e) {
        this.$toast.fail('登录失败')
      }
      this.isDone = false
    }
  }
}
</script>

<style lang="less" scoped></style>
